package com.example.demo.intercepter;

import com.example.demo.annotation.Authorization;
import com.example.demo.model.User;
import com.example.demo.service.TokenService;
import com.example.demo.util.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private TokenService service;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 如果方法注明了Authorization
        Authorization annotaion = AnnotationUtils.findAnnotation(method, Authorization.class);
        if (annotaion != null) {
            // 从header中得到token
            String token = request.getHeader(Const.AUTHORIZATION_HEADER);
            // 验证token
            User model = service.checkToken(token);
            if (model != null) {
                // 如果token验证成功，将token对应的用户id存在request中，便于之后注入
                request.setAttribute(Const.CURRENT_USER, model);
                return true;
            }

            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    }
}
